var CommissionPayModule = function () {
    var editable = function () {

        return {
            init: function () {
            	Date.prototype.format = function(format){
                	var o = {
                	"M+": this.getMonth() + 1, //month
                	"d+": this.getDate(), //day
                	"h+": this.getHours(), //hour
                	"m+": this.getMinutes(), //minute
                	"s+": this.getSeconds(), //second
                	"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
                	"S": this.getMilliseconds() //millisecond
                	}
                	if (/(y+)/.test(format))
                	format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                	for (var k in o)
                	if (new RegExp("(" + k + ")").test(format))
                	format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                	return format;
                }
                
                function GetDateStr(AddDayCount){
                    var dd = new Date();
                     dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
                     return dd.format('yyyy-MM-dd');
                }

                //初始化日期输入框
                function initDateInput(){
                	document.getElementById('payEndTime').value = GetDateStr(0);
                	document.getElementById('payStartTime').value = GetDateStr(-29);
                }
                
                initDateInput();
                
                $("#productSearch").autocomplete({
                    source: function(query,process){
                    	$.ajax({
    	                	"contentType":"application/json; charset=UTF-8",
                            "dataType" : 'json',
                            "type" : "POST",
                            "url" : ctx + "/orders/product/"+query.term+"/0",
                            "data" : {"matchCount":200},
                            "success" : function(data){
                            	var ebean = []
                            	for (var int = 0; int < data.length; int++) {
                            		var temp = [];
                            		temp.label = data[int].briefName +"  "+ data[int].productCode;
                            		temp.value = data[int].briefName +"  "+ data[int].productCode;
                            		temp.productId = data[int].productId;
                            		ebean.push(temp);
                        		}
                                return process(ebean);
                            }
    	                })
                    },
                    search:function(event, ui){
                    	$("#productId").val("");
                    },
                    select: function(event, ui) {
                        $("#productSearch").val(ui.item.label);
                        $("#productId").val(ui.item.productId);
                        var uistr =ui.item;
                        // 阻止事件的默认行为
                        event.preventDefault(); 
                    }
                });
            	
                var oTable = $('#modelEditable').dataTable({
                	"autoWidth":false,
                	"lengthMenu": [
                                   [10, 15, 20, 50],
                                   [10, 15, 20, 50]
                               ],
                    "displayLength": 10,
                    "scrollX":true,
                    "language": {
                       "lengthMenu": "每页 _MENU_ 条记录",
                       "zeroRecords":"数据为空",
                       "paginate": {
                           "previous": "上一页",
                           "next": "下一页"
                       },
                       "info" : "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",    
                       "infoEmpty" : "记录数为0",
                     },
                    "columnDefs": [
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [0]
            						},
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [1]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [2]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [3]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "<center>--</center>",
            						    "targets": [4]
            						}, 
            						{
            						    "data": null,
            						    'sortable': false,
            						    "defaultContent": "Edit",
            						    "targets": [5]
            						}, 
                                ],
                   "columns": [{ "data": "employeeName" },
                                { "data": "orderTotalAmount" },
                                { "data": "totalCommission" },
                                { "data": "settledAmount"},
                                { "data": "unsettledAmount" },],
                   "filter" : false,
                   "processing": false,
                   "serverSide": true,
                   "ajaxSource": ctx + "/commissionPay/queryTotal",
                   "serverMethod": "post",
                   "fnRowCallback" : function(nRow, aData, displayIndex) {
                	   nRow.children[0].id = aData.employeeId;
                	   $('td:eq(0)', nRow).html("<center>"+aData.employeeName+"<br>工号："+aData.employeeNo+"</center>");    	   
                	   $('td:eq(1)', nRow).html(formatCurrency(aData.orderTotalAmount)+"&nbsp;元");
                	   $('td:eq(2)', nRow).html(formatCurrency(aData.totalCommission)+"&nbsp;元");
                	   $('td:eq(3)', nRow).html(formatCurrency(aData.settledAmount)+"&nbsp;元");
                	   $('td:eq(4)', nRow).html(formatCurrency(aData.unsettledAmount)+"&nbsp;元");
                	   var opera = '<a class="detail fa fa-bars fa-lg" title="明细" href="javascript:;"></a>';
                	   $('td:eq(5)', nRow).html(opera);
                       return nRow;
                   },
                   "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                   var json = "";
	                   var s;
	                   for (var i = 0; i < dataSet.length; i++) {
	                       s = dataSet[i];
	                   	   if (s.name == 'sEcho') {
	                   		   json = json + '"echo":' + s.value;
		                   } else if (s.name == 'iDisplayStart') {
		                	   json = json + ',"start":' + s.value;
		                   } else if (s.name == 'iDisplayLength') {
		                	   json = json + ',"pageSize":' + s.value;
		                   }
	                   }
	                   var form = $("form#queryForm").serializeJSON();
                   	   var js = form.replace('}', ',');
                   	   json = js + json + "}";
                       $.ajax({
                       	"contentType":"application/json; charset=UTF-8",
                           "dataType" : 'json',
                           "type" : "POST",
                           "url" : ajaxSource,
                           "data" : json,
                           "success" : fnCallback
                       });
                       //再一次发送请求获取总额内容并渲染
                       $.ajax({
                          	"contentType":"application/json; charset=UTF-8",
                              "dataType" : 'json',
                              "type" : "POST",
                              "url" : ajaxSource,
                              "data" : json,
                              "success" : function(msg){
                            	  $('#sumOrderAmountTd').html('销售总额: ' + formatCurrency(msg.sumOrderAmount)+"&nbsp;元");
                                  $('#sumCommissionTd').html('佣金总额: ' + formatCurrency(msg.sumCommission)+"&nbsp;元");
                                  $('#sumSettleTd').html('已结算: ' + formatCurrency(msg.sumSettle)+"&nbsp;元");
                                  $('#sumUnsettleTd').html('未结算: ' + formatCurrency(msg.sumUnsettle)+"&nbsp;元");
                              }
                       });
                   },
                });
                // 明细
                $('#modelEditable').on("click", "a.detail", (function (e) {
                    e.preventDefault();

                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                	
                    window.location.href = "commissionPay/empList/"+id;
                }));
                
                $('#detailTotal').click(function(){
                	window.location.href = "commissionPay/listTotal?payStartTime="+$('#payStartTime').val()
                	+"&payEndTime="+$('#payEndTime').val()
                	+"&productSearch="+$('#productSearch').val()
                	+"&productId="+$('#productId').val()
                	+"&state="+$('#state').val();
                });
                
                $('#queryBtn').click(function(){
                	oTable.fnClearTable();
                });
                
                // 导出excel
                $('#exportExcel').click(function(){
                	var json = $("form#queryForm").serializeJSON();
                	
                	var form=$("<form>");
                	form.attr("style","display:none");
                	form.attr("target","");
                	form.attr("method","post");
                	form.attr("action",ctx + "/commissionPay/statsDownload");
                	
                	var paramsInput=$("<input>");
                	paramsInput.attr("type","hidden");
                	paramsInput.attr("name","params");
                	paramsInput.attr("value", json);
                	
                	form.append(paramsInput);
                	
                	$("body").append(form);
                	
                	form.submit();
                });
                
            }

        };

    }();
    
    return {
        init: function () {
        	editable.init();
        }
    };
}();